package com.hcinfos.gsoo.ui;

import java.util.ArrayList;
import java.util.List;

import com.easemob.chat.EMChatManager;
import com.easemob.chatuidemo.activity.MainActivity;
import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.adapter.MainFocusAdapter;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.db.DBUtil;
import com.hcinfos.gsoo.enity.City;
import com.hcinfos.gsoo.service.LocationService;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class OnlineOrderMainActivity extends Activity implements
		OnPageChangeListener, OnClickListener {

	private ViewPager viewPager;
	private LinearLayout viewGroup;
	private ImageView[] imageViews;
	private ImageView imageView;
	private MainFocusAdapter adapter;

	private LinearLayout recommend_ll;
	private List<String> recommendList;

	private RelativeLayout waimai_rl;
	private RelativeLayout yuding_rl;

	private ImageView menu_iv;
	private ImageView right_iv;
	private SharePreferenceUtil util;

	private DBUtil dbUtil;
	private ImageView red_iv;
	private TextView unread_msg_number;
	private NewMessageBroadcastReceiver msgReceiver;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		dbUtil = DBUtil.newInstance(this);
		setContentView(R.layout.activity_online_main);
		IntentFilter filter = new IntentFilter(LocationService.LOCATION_ACTION);
		registerReceiver(locationReceiver, filter);

		msgReceiver = new NewMessageBroadcastReceiver();
		IntentFilter intentFilter = new IntentFilter(EMChatManager
				.getInstance().getNewMessageBroadcastAction());
		intentFilter.setPriority(3);
		registerReceiver(msgReceiver, intentFilter);
		util = new SharePreferenceUtil(this, "setting");
		recommendList = new ArrayList<String>();
		recommendList.add("大牌 '食' 界杯");
		recommendList.add("父亲节特惠");
		recommendList.add("好酒送慈父");

		unread_msg_number = (TextView) findViewById(R.id.unread_msg_number);
		recommend_ll = (LinearLayout) findViewById(R.id.recommend_ll);
		viewPager = (ViewPager) findViewById(R.id.viewpager);
		viewGroup = (LinearLayout) findViewById(R.id.viewGroup);
		List<String> list = new ArrayList<String>();
		list.add("tes1");
		list.add("tes2");
		imageViews = new ImageView[list.size()];
		for (int i = 0; i < list.size(); i++) {
			LinearLayout.LayoutParams parmas = new LinearLayout.LayoutParams(
					12, 12);
			parmas.leftMargin = 5;
			parmas.rightMargin = 5;
			imageView = new ImageView(this);
			imageView.setLayoutParams(parmas);
			imageViews[i] = imageView;
			if (i == 0) {
				imageView.setBackgroundResource(R.drawable.new_focus_icon);
			} else {
				imageView.setBackgroundResource(R.drawable.new_unfocus_icon);
			}
			viewGroup.addView(imageView);
		}

		adapter = new MainFocusAdapter(list, this);
		MainFocusAdapter.test = 1;
		viewPager.setAdapter(adapter);
		viewPager.setOnPageChangeListener(this);
		viewPager.setCurrentItem(0);

		waimai_rl = (RelativeLayout) findViewById(R.id.waimai_rl);
		waimai_rl.setOnClickListener(this);
		yuding_rl = (RelativeLayout) findViewById(R.id.yuding_rl);
		yuding_rl.setOnClickListener(this);
		menu_iv = (ImageView) findViewById(R.id.left_iv);
		menu_iv.setOnClickListener(this);
		right_iv = (ImageView) findViewById(R.id.right_iv);
		right_iv.setOnClickListener(this);
		updateViews();

		red_iv = (ImageView) findViewById(R.id.red_iv);
	}

	private class NewMessageBroadcastReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			int count = getUnreadMsgCountTotal();
			if (count > 0) {

				unread_msg_number.setText(count + "");
				unread_msg_number.setVisibility(View.VISIBLE);
			} else {
				unread_msg_number.setVisibility(View.GONE);
			}
		}
	}

	public int getUnreadMsgCountTotal() {
		int unreadMsgCountTotal = 0;
		unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
		return unreadMsgCountTotal;
	}

	BroadcastReceiver readReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			int number = intent.getIntExtra("number", 0);
			if (number == 0) {
				unread_msg_number.setVisibility(View.GONE);
			} else {
				unread_msg_number.setText(number + "");
				unread_msg_number.setVisibility(View.VISIBLE);
			}
		}

	};

	@Override
	protected void onResume() {

		if (GsooApplication.isShowTipChangeCity) {
			doLcationTip();
		}
		super.onResume();
	}

	private void doLcationTip() {
		City city = (City) util.loadObject("city");
		try {
			if (city != null) {
				if (GsooApplication.lat == null) {
					Intent locationService = new Intent(this,
							LocationService.class);
					startService(locationService);
				} else {
					if (GsooApplication.cityName != null
							&& !GsooApplication.cityName.equals(city.getName())) {
						changeCityDialog();
						info_tv.setText("定位错了，我不在" + GsooApplication.cityName
								+ "...");
						location_tv.setText("定位显示你在" + GsooApplication.cityName
								+ "，你还可以....");
						change_btn.setText("切换到" + GsooApplication.cityName);
						go_btn.setText("继续浏览" + city.getName());
					}
				}

			} else {
				// 城市未开通
			}
		} catch (Exception e) {

			LogUtil.e("wxf", "obtainData =" + e.toString());
		}
	}

	protected void onDestroy() {

		if (locationReceiver != null)
			unregisterReceiver(locationReceiver);
		if (readReceiver != null)
			unregisterReceiver(readReceiver);

		if (msgReceiver != null)
			unregisterReceiver(msgReceiver);
		super.onDestroy();
	};

	BroadcastReceiver locationReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			doLcationTip();
			LogUtil.d("wxf", "HomeActivity  location Receiver........");
		}

	};
	private String id = "";

	private void updateViews() {
		recommend_ll.removeAllViews();
		for (int i = 0; i < recommendList.size(); i++) {
			View view = getLayoutInflater().from(this).inflate(
					R.layout.online_order_item, null);
			TextView name_tv = (TextView) view.findViewById(R.id.name_tv);
			name_tv.setText(recommendList.get(i));
			ImageView icon_iv = (ImageView) view.findViewById(R.id.icon_iv);
			switch (i) {
			case 0:
				icon_iv.setImageResource(R.drawable.online_test);
				break;
			case 1:
				icon_iv.setImageResource(R.drawable.online_test2);

				break;
			case 2:
				icon_iv.setImageResource(R.drawable.online_test3);

				break;
			}
			view.setTag(i);
			view.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					int i = (Integer) v.getTag();
					if (i == 0) {
						id = "ae0b71488e3949b2804cee5b15aa5d81";
					} else if (i == 1) {
						id = "e9e1e8362c1a4d7a8a7287d3874e13f3";
					} else {
						id = "be612aa8028849f38095e5e3c2fb9d36";
					}
					Intent intent = new Intent(OnlineOrderMainActivity.this,
							ShopDetailActivity.class);
					intent.putExtra("suppId", id);
					startActivity(intent);
				}
			});
			recommend_ll.addView(view);
		}
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	@Override
	public void onPageSelected(int position) {
		setImageBackground(position);
		switch (position) {
		case 0:
			GsooApplication.sildingMenu
					.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
			break;
		default:
			GsooApplication.sildingMenu
					.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
			break;
		}
	}

	private void setImageBackground(int selectItems) {
		for (int i = 0; i < imageViews.length; i++) {
			if (i == selectItems) {
				imageViews[i].setBackgroundResource(R.drawable.new_focus_icon);
			} else {
				imageViews[i]
						.setBackgroundResource(R.drawable.new_unfocus_icon);
			}
		}
	}

	long waitTime = 2000;
	long touchTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& KeyEvent.KEYCODE_BACK == keyCode) {
			GsooApplication.isShowTipChangeCity = false;
			long currentTime = System.currentTimeMillis();
			if ((currentTime - touchTime) >= waitTime) {
				Toast.makeText(this, "再按一次退出", Toast.LENGTH_SHORT).show();
				touchTime = currentTime;
			} else {
				finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private Intent intent;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.waimai_rl:
			intent = new Intent(this, WaimaiListActivity.class);
			startActivity(intent);
			break;
		case R.id.yuding_rl:
			intent = new Intent(this, DingzuoListActivity.class);
			startActivity(intent);
			break;
		case R.id.left_iv:
			if (GsooApplication.sildingMenu != null)
				GsooApplication.sildingMenu.toggle();
			break;
		case R.id.right_iv:
			if (util.loadObject("user") == null) {
				Intent intent = new Intent(OnlineOrderMainActivity.this,
						LoginActivity.class);
				startActivity(intent);
			} else {
				unread_msg_number.setVisibility(View.GONE);
				intent = new Intent(OnlineOrderMainActivity.this,
						MainActivity.class);
				startActivity(intent);
			}
			break;
		case R.id.change_btn:
			changeCity();
			dialog.dismiss();
			break;
		case R.id.go_btn:
			GsooApplication.isShowTipChangeCity = false;
			dialog.dismiss();
			break;
		case R.id.close_iv:
			GsooApplication.isShowTipChangeCity = false;
			dialog.dismiss();
			break;
		}
	}

	private void changeCity() {
		City city = dbUtil.queryCityByCityName(GsooApplication.cityName);
		if (city != null) {
			util.saveObject(city, "city");
		}
	}

	/**
	 * 城市切换提示dialog
	 */
	private Dialog dialog;
	private Button change_btn;
	private Button go_btn;
	private ImageView close_iv;
	private TextView info_tv;
	private TextView location_tv;

	private void changeCityDialog() {

		LayoutInflater inflater = getLayoutInflater();
		RelativeLayout dialog_rl = (RelativeLayout) inflater.inflate(
				R.layout.changecity_dialog_view, null);
		change_btn = (Button) dialog_rl.findViewById(R.id.change_btn);
		change_btn.setOnClickListener(this);
		go_btn = (Button) dialog_rl.findViewById(R.id.go_btn);
		go_btn.setOnClickListener(this);
		close_iv = (ImageView) dialog_rl.findViewById(R.id.close_iv);
		close_iv.setOnClickListener(this);
		location_tv = (TextView) dialog_rl.findViewById(R.id.location_tv);
		info_tv = (TextView) dialog_rl.findViewById(R.id.info_tv);

		dialog = new Dialog(this, R.style.QuitDialog);
		dialog.setContentView(dialog_rl);
		Window dialogWindow = dialog.getWindow();
		WindowManager.LayoutParams lp = dialogWindow.getAttributes();
		dialogWindow.setGravity(Gravity.CENTER);
		lp.width = (int) (260 * Common.PROPORTION); // 宽度
		lp.height = (int) (220 * Common.PROPORTION); // 高度
		dialogWindow.setAttributes(lp);
		dialog.show();
	}

}
